<template>
  <view>
    <!-- 摄像头 -->
    <camera device-position="back" flash="off" @error="handleCameraError" style="width: 100%; height: 80vh;"></camera>
    <button @click="takePhoto">拍照</button>

    <!-- Canvas 选择部分区域 -->
    <canvas
      type="2d"
      id="myCanvas"
      class="canvaspic"
      style="width: 100%; height: 80vh;"
      @touchstart="startInteraction"
      @touchmove="handleInteraction"
      @touchend="endInteraction"
    ></canvas>

    <!-- 上传按钮 -->
    <button @click="uploadSelectedArea">上传选择的部分</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tempImagePath: '', // 拍照后临时图片路径
      selectedArea: { x: 50, y: 50, width: 100, height: 100 }, // 用户选择的区域
      isDragging: false, // 是否正在拖动
      isResizing: false, // 是否正在调整大小
      resizingCorner: null, // 调整大小的角
      startX: 0, // 拖动开始的X坐标
      startY: 0, // 拖动开始的Y坐标
      minWidth: 20, // 框的最小宽度
      minHeight: 20, // 框的最小高度
    };
  },
  methods: {
    takePhoto() {
      const context = wx.createCameraContext();
      context.takePhoto({
        quality: 'high',
        success: (res) => {
          this.tempImagePath = res.tempImagePath;
          this.drawImageOnCanvas(res.tempImagePath);
        },
        fail: (err) => {
          console.error('拍照失败：', err);
        }
      });
    },
    drawImageOnCanvas(imagePath) {
      const query = wx.createSelectorQuery();
      query.select('#myCanvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          const img = canvas.createImage();

          img.src = imagePath;
          img.onload = () => {
            // 绘制图片到 Canvas 上
            ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

            // 绘制红色选框
            this.drawSelection(ctx);
          };
        });
    },
    drawSelection(ctx) {
      // 绘制用户选中的区域
      ctx.strokeStyle = 'red';
      ctx.lineWidth = 2;
      ctx.strokeRect(this.selectedArea.x, this.selectedArea.y, this.selectedArea.width, this.selectedArea.height);

      // 绘制控制点（角点）
      const cornerRadius = 10; // 控制点的半径
      ctx.fillStyle = 'blue';
      const corners = this.getCorners();
      corners.forEach(corner => {
        ctx.beginPath();
        ctx.arc(corner.x, corner.y, cornerRadius, 0, 2 * Math.PI);
        ctx.fill();
      });
    },
    getCorners() {
      const { x, y, width, height } = this.selectedArea;
      return [
        { x, y }, // 左上角
        { x: x + width, y }, // 右上角
        { x, y: y + height }, // 左下角
        { x: x + width, y: y + height } // 右下角
      ];
    },
    startInteraction(e) {
      const touch = e.touches[0];
      this.startX = touch.pageX;
      this.startY = touch.pageY;

      const corners = this.getCorners();
      const radius = 20; // 控制点的触摸范围（增大检测范围）
      this.isDragging = true;
      this.isResizing = false;
      
      // 判断是否在控制点上
      for (let i = 0; i < corners.length; i++) {
        const dx = touch.pageX - corners[i].x;
        const dy = touch.pageY - corners[i].y;
        if (dx * dx + dy * dy <= radius * radius) {
          this.isResizing = true;
          this.resizingCorner = i;
          this.isDragging = false; // 如果点击到控制点，不允许拖动
          break;
        }
      }
    },
    handleInteraction(e) {
      if (this.isDragging) {
        this.dragSelection(e);
      } else if (this.isResizing) {
        this.resizeSelection(e);
      }
    },
    dragSelection(e) {
      const touch = e.touches[0];
      const offsetX = touch.pageX - this.startX;
      const offsetY = touch.pageY - this.startY;

      this.selectedArea.x += offsetX;
      this.selectedArea.y += offsetY;

      this.startX = touch.pageX;
      this.startY = touch.pageY;

      // 重新绘制图片和选框
      this.redrawCanvas();
    },
    resizeSelection(e) {
      const touch = e.touches[0];
      const { selectedArea } = this;
      const offsetX = touch.pageX - this.startX;
      const offsetY = touch.pageY - this.startY;

      switch (this.resizingCorner) {
        case 0: // 左上角
          selectedArea.x += offsetX;
          selectedArea.y += offsetY;
          selectedArea.width -= offsetX;
          selectedArea.height -= offsetY;
          break;
        case 1: // 右上角
          selectedArea.y += offsetY;
          selectedArea.width += offsetX;
          selectedArea.height -= offsetY;
          break;
        case 2: // 左下角
          selectedArea.x += offsetX;
          selectedArea.width -= offsetX;
          selectedArea.height += offsetY;
          break;
        case 3: // 右下角
          selectedArea.width += offsetX;
          selectedArea.height += offsetY;
          break;
      }

      // 确保选框的宽高不小于最小值
      if (selectedArea.width < this.minWidth) {
        selectedArea.width = this.minWidth;
      }
      if (selectedArea.height < this.minHeight) {
        selectedArea.height = this.minHeight;
      }

      this.startX = touch.pageX;
      this.startY = touch.pageY;

      // 重新绘制图片和选框
      this.redrawCanvas();
    },
    endInteraction() {
      this.isDragging = false;
      this.isResizing = false;
    },
    redrawCanvas() {
      const query = wx.createSelectorQuery();
      query.select('#myCanvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          const img = canvas.createImage();

          img.src = this.tempImagePath;
          img.onload = () => {
            // 清空画布并重新绘制图片和选框
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            this.drawSelection(ctx);
          };
        });
    },
    uploadSelectedArea() {
      const query = wx.createSelectorQuery();
      query.select('#myCanvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');

          // 获取选定区域
          const imageData = ctx.getImageData(this.selectedArea.x, this.selectedArea.y, this.selectedArea.width, this.selectedArea.height);

          // 创建一个新的 Canvas 裁剪该区域
          const tempCanvas = canvas.createOffscreenCanvas(this.selectedArea.width, this.selectedArea.height);
          const tempCtx = tempCanvas.getContext('2d');
          tempCtx.putImageData(imageData, 0, 0);

          // 将选中的区域转换为临时图片路径
          wx.canvasToTempFilePath({
            canvas: tempCanvas,
            success: (res) => {
              console.log('裁剪后的图片路径:', res.tempFilePath);
              this.uploadImage(res.tempFilePath);
            },
            fail: (err) => {
              console.error('裁剪失败:', err);
            }
          });
        });
    },
    uploadImage(filePath) {
      // 上传图片到服务器
      wx.uploadFile({
        url: 'https://your-server/upload', // 服务器地址
        filePath: filePath,
        name: 'file',
        success: (res) => {
          console.log('上传成功:', res);
        },
        fail: (err) => {
          console.error('上传失败:', err);
        }
      });
    },
    handleCameraError(err) {
      console.error('摄像头错误：', err);
    }
  }
};
</script>

<style scoped>
.canvaspic {
  border: 1px solid #ccc;
}
</style>
